<template>
  <section class="cms-page">
    <h2 class="cms-title">{{edit_type}}资讯</h2>
    <el-form
      v-loading="loading"
      element-loading-text="加载资讯详情中..."
      class="cms-form"
      ref="form"
      :model="form"
      label-width="80px">
      <el-form-item
        label="标题："
        prop="title"
        :rules="[{required: true, message:'请输入标题'}]"
      >
        <el-input v-model="form.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item
        label="封面图："
        prop="header_url"
        :rules="[{required: true, message:'请上传封面图'}]"
      >
        <el-upload
          action="/api/v1/image"
          :on-remove="handleRemove"
          :http-request="handleUpload"
          :file-list="img_list"
          list-type="picture">
          <el-button
            :loading="upload_loading"
            size="small"
            type="primary">点击上传
          </el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item
        label="内容"
        prop="content"
        :rules="[{required: true, message: '请输入内容'}]"
        class="cms-editor"
      >
        <div id="editor"></div>
      </el-form-item>
      <el-form-item
        label=" "
      >
        <el-button
          :loading="submit_loading"
          :disabled="disabled"
          @click="submit"
          type="primary">确定
        </el-button>
      </el-form-item>
    </el-form>
  </section>
</template>

<script>
  /**
   * @Author: lifuzhao
   * @Date: 2019-05-15
   * @Project: eabax
   */
  let E
  console.log(process)
  if (process.browser) {
    E = require('wangeditor')
  }
  export default {
    name: 'edit',
    data() {
      return {
        loading: false,
        upload_loading: false,
        submit_loading: false,
        img_list: [],
        form: {
          title: '',
          header_url: '',
          content: ''
        }
      }
    },
    computed: {
      edit_type() {
        let query = this.$route.query
        return query.id ? '编辑' : '新增'
      },
      url() {
        let query = this.$route.query
        return query.id ? '/api/v1/information/update' : '/api/v1/information/save'
      },
      disabled() {
        let form = this.form,
          query = this.$route.query,
          keys = ['title', 'header_url', 'content'],
          disabled = false
        keys.forEach(key => {
          if (key === 'header_url' && query.id) {
            return
          }
          if (!form[key]) {
            disabled = true
          }
        })
        return disabled
      }
    },
    watch: {
      $route: {
        deep: true,
        handler() {
          this.init()
        }
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      init() {
        this.form = {
          title: '',
          header_url: '',
          content: ''
        }
        let query = this.$route.query
        if (query.id) {
          this.getArticleDetail(query.id)
        }
        this.createEditor()
      },
      getArticleDetail(id) {
        this.loading = true
        this.$axios
          .$get('/api/v1/information', {
            params: {
              id: id
            }
          })
          .then(res => {
            this.loading = false
            this.form.title = res.title
            this.img_list = [{
              name: '封面图.jpg',
              url: res.header_url
            }]
            this.editor.txt.html(JSON.parse(res.content))
            this.editor.change()
          })
          .catch(res => {
            this.loading = false
            this.$message({
              type: 'error',
              message: '获取资讯详情失败'
            })
          })
      },
      handleRemove() {
        this.img_list = []
      },
      async handleUpload(file_item) {
        let base64 = await this.$fn.getBase64(file_item.file)
        this.img_list = []
        this.upload_loading = true
        this.$axios.$post('/api/v1/image', {
          img: this.$fn.extractBase64(base64)
        })
          .then(res => {
            this.upload_loading = false
            this.form.header_url = res.id
            this.img_list = [{
              name: '封面图.jpg',
              url: base64
            }]
          }, err => {
            this.upload_loading = false
            this.$message({
              message: '上传图片失败',
              type: 'error'
            })
          })
      },
      createEditor() {
        this.editor = new E('#editor')
        this.editor.customConfig.pasteIgnoreImg = true
        this.editor.customConfig.uploadImgShowBase64 = true
        this.editor.customConfig.zIndex = 100
        this.editor.customConfig.menus = [
          'head',  // 标题
          'bold',  // 粗体
          'fontSize',  // 字号
          'fontName',  // 字体
          'italic',  // 斜体
          'underline',  // 下划线
          'strikeThrough',  // 删除线
          'foreColor',  // 文字颜色
          'backColor',  // 背景颜色
          'link',  // 插入链接
          'list',  // 列表
          'justify',  // 对齐方式
          'quote',  // 引用
          'image',  // 插入图片
          'table',  // 表格
          'undo',  // 撤销
          'redo'  // 重复
        ]
        this.editor.customConfig.onchange = html => {
          this.form.content = JSON.stringify(html)
          this.form.sub_content = this.editor.txt.text().slice(0, 200)
        }
        this.editor.customConfig.customUploadImg = async (files, insert) => {
          let file = files[0] || {},
            base64 = await this.$fn.getBase64(file),
            img = this.$fn.extractBase64(base64)
          let message = this.$message({
            message: '上传图片中...',
            type: 'info',
            iconClass: 'el-icon-loading',
            duration: 0
          })
          let res = await this.$axios
            .$post('/api/v1/image/url', {
              img: img
            })
          message.close()
          if(res.url){
            this.$message({
              type: 'success',
              message: '上传成功'
            })
            insert(res.url)
          }else{
            this.$message({
              type: 'error',
              message: '上传失败'
            })
          }
        }
        this.editor.create()
      },
      submit() {
        let form = this.form,
          url = this.url,
          query = this.$route.query,
          disabled = this.disabled
        if (disabled) return
        let data = this.form
        if (query.id) {
          data.id = query.id
          if (!form.header_url) {
            delete form.header_url
          }
        }
        this.submit_loading = true
        this.$axios
          .post(url, data)
          .then(res => {
            this.submit_loading = false
            this.$message({
              message: this.edit_type + '成功',
              type: 'success'
            })
            this.$router.push({
              path: '/cms/article'
            })
          })
          .catch(res => {
            this.submit_loading = false
            this.$message({
              message: this.edit_type + '失败',
              type: 'error'
            })
          })

      }
    },
    layout: 'cms'
  }
</script>

<style lang="less">
  .cms-form {
    .el-form-item {
      max-width: 600px;
    }

    .cms-editor {
      max-width: 1000px;
    }

  }
</style>
